<template>
    <div class="hostel">
      <div class="search">
        房屋编号：
        <el-input
          style="width: 145px; padding-right:10px"
          placeholder="请输入房屋编号"
          prefix-icon="el-icon-search"
          v-model="searchData.hostelCode">
        </el-input>

        楼宇名称：
        <el-select style="width: 180px;" v-model="searchData.buildId" placeholder="请选择楼宇">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
  
        <el-button style=" float: right; margin-left:10px;" @click="reset">重置</el-button>
        <el-button style=" float: right;" type="primary" @click="onSubmit">查询</el-button>
      </div>
  
      <div class="do">
        <el-button v-if="user.position === 2 || user.position === 1" style="margin-left:10px;" @click="dialogFormVisible = true">新增</el-button>
        <el-button v-if="user.position === 2" @click="batchDelete()">批量删除</el-button>
      </div>
  
      <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      stripe
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        prop="hostelCode"
        label="房屋号码">
      </el-table-column>
      <el-table-column
        prop="area"
        label="房屋面积(㎡)">
      </el-table-column>
      <el-table-column
        prop="buildName"
        label="楼宇名称">
      </el-table-column>
      <el-table-column
        prop="tag"
        label="标签"
        :filters="[{ text: '未出售', value: 0 }, { text: '已出售', value: 1 }]"
        :filter-method="filterTag"
        filter-placement="bottom-end">
        <template slot-scope="scope">
            <el-tag
            :type="scope.row.status === 0 ? 'primary' : 'success'"
            disable-transitions>{{getStatusText(scope.row.status)}}</el-tag>
        </template>
      </el-table-column>  
      <el-table-column
        prop="username"
        label="业主">
      </el-table-column>
      <el-table-column  v-if="user.position === 2 || user.position === 1" label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
             v-if="user.position === 2"
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
      </el-table>
  
      <div class="block" style="margin-top: 20px; text-align: right; margin-right: 20px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
        </el-pagination>
      </div>
  
      <HostelFormPop class="houseFormPop" @updateFormData="updateFormData" :userOptions="userOptions" :options="options" :title.sync="title" :formData="updateTableData" v-show="dialogFormVisible" :visible.sync="dialogFormVisible"></HostelFormPop>
    </div>
  </template>
  
  <script>
  import api from '@/api';
  import HostelFormPop from './HostelFormPop.vue';
  import { mapState,mapMutations } from "vuex"
  
  export default {
    computed:{
      ...mapState("login",["user"])
    },
      components: {
        HostelFormPop,
      },
      data() {
        return {
          options:[],
          userOptions:[],
          title: '新增房屋',
          currentPage: 1,
          total:100,
          pageSize:10,
          dialogFormVisible: false,
          options:[],
          searchData:{
            hostelCode: '',
            buildId:'',
            pageNow: 1,
          },
          tableData: [{
            id:'',
            hostelCode: '302',
            buildName: '状元楼',
            buildId:'',
            status: 0,
            username:'',
            userId:"",
            area:"",
          }],
          selectedRow:[],
          updateTableData:{
            id:'',
            hostelCode: '',
            buildName: '',
            buildId:'',
            status: 0,
            username:'',
            userId:"",
            area:"",
          }
        }
      },
      methods: {
        updateFormData(data){
          this.updateTableData = data;
        },
        getStatusText(status){
            switch(status){
              case 0 : return '未出售';
              case 1 : return '已出售';
              default : return '';
            }
        },
        handleSizeChange(val) {
          console.log(`每页 ${val} 条`);
        },
        handleCurrentChange(val) {
           this.searchData.pageNow = val
           //获取房屋信息
           this.onSubmit();
        },
        handleSelectionChange(selection) {
            this.selectedRow = selection
        },
        handleEdit(index, row) {
          this.updateTableData = row;
          this.dialogFormVisible = true;
          this.title = '编辑房屋'
        },
        handleDelete(index, row) {
          api.hostelDelete(row.id).then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                this.$message.error('删除成功')
                this.tableData.splice(index,1)
              }else{
                this.$message.error(res.data.message)
              }
          })
        },
        filterTag(value, row) {
          return row.status === value;
        },
        //批量删除
        batchDelete(){
          var deleteIds = '';
          this.selectedRow.map(item =>{
            if(deleteIds === ''){
              deleteIds = item.id
            }else{
              deleteIds = deleteIds + "," + item.id
            }
          })
          if(deleteIds === ''){
            this.$message.error("请勾选删除项")
            return;
          }
          api.hostelDelete(deleteIds).then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                this.$message.success('删除成功');
                this.selectedRow.map(item =>{
                  const index = this.tableData.findIndex((data) => data.id === item.id);
                  this.tableData.splice(index,1)
                })
              }else{
                this.$message.error(res.data.message)
              }
          })
        },
        onSubmit() {
          //获取房屋信息
          api.hostelList(this.searchData).then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                let noticeInfoDTO = res.data.data.hostelInfos

                // 将 options 数组转换为以 value 为键、label 为值的对象
                const optionsMap = this.options.reduce((map, option) => {
                      map[option.value] = option.label;
                      return map;
                  }, {});
                const userOptionsMap = this.userOptions.reduce((map, option) => {
                      map[option.value] = option.label;
                      return map;
                  }, {});
                  noticeInfoDTO.forEach(item => {
                      if (item.buildId) {
                          // 使用 map 方法和 optionsMap 构建 receivers 数组
                          const buildName = optionsMap[item.buildId];
                          item.buildName = buildName;
                      }
                      if(item.userId){
                          const username = userOptionsMap[item.userId];
                          item.username = username;
                      }
                });
                this.tableData = noticeInfoDTO
                console.log(noticeInfoDTO)
                this.total = res.data.data.total
              }else{
                this.$message.error(res.data.message)
              }
          })
        },
        // 重置
        reset(){
          this.searchData.hostelCode = '',
          this.searchData.buildId = '',
          this.onSubmit();
        },
        //查询楼宇信息
        getReceivers() {
          return new Promise((resolve, reject) => {
              api.buildListAll().then(res => {
                if (res.type === 'error') {
                  this.$message.error(res.message);
                  reject(res.message);
                } else if (res.data.code === 200) {
                  const tableData = res.data.data.buildInfos;
                  this.options = tableData.map(item => ({
                    value: item.id,
                    label: item.buildingName + "-" + item.unit
                  }));
                  resolve();
                } else {
                  this.$message.error(res.data.message);
                  reject(res.data.message);
                }
              });
            });
        },
        //查询用户信息
        getUserInfo(){
          api.getUserByPosition(false,false,{}).then(res => {
                if (res.type === 'error') {
                  this.$message.error(res.message);
                } else if (res.data.code === 200) {
                  const userList = res.data.data.userList;
                  this.userOptions = userList.map(item => ({
                    value: item.id,
                    label: item.username
                  }));
                } else {
                  this.$message.error(res.data.message);
                }
          });
        }
      },
      created () {
        this.getUserInfo()
        //获取房屋信息
        this.getReceivers().then(() => {
          this.onSubmit(); // 确保 buildName 解析时 options 已加载
        });
      },
  }
  </script>
  <style scoped>
  .hostel{
    background-color: #fff;
  }
  .hostel .search{
    padding: 10px;
  }
  .hostel .do{
    padding: 10px;
  }
  /* 自定义遮罩层样式 */
  .hostel .houseFormPop {
    background-color: rgba(0, 0, 0, 0.5); /* 遮罩层颜色 */
    z-index: 9999; /* 设置一个较高的 z-index 使遮罩层位于最上层 */
  }
  </style>